#main.py
import sys, time
import threading
import binascii
import json
import nnpy

class Router(object):
    """docstring for Router"""
    local_url = "ipc:///tmp/router.ipc"
    web_url = "ipc:///tmp/web.ipc"
    drive_url = "ipc:///tmp/drive.ipc"
    servo_url = "ipc:///tmp/servo.ipc"
    uart_url = "ipc:///tmp/uart.ipc"
    remote_urls = [web_url, servo_url, drive_url, uart_url]


    DEVICE_NAME = "router"

    def __init__(self):
        super(Router, self).__init__()
        self.MODE_DICT = {
            "request": self.proc_mode_request,
            "reply": self.proc_mode_reply,
            "forward": self.proc_mode_forward,
        }

        self.OPERAT_DICT = {
            "oauth_test" : self.oauth_test,

        }

        self.local_sock = nnpy.Socket(nnpy.AF_SP, nnpy.BUS)
        self.local_sock.bind(self.local_url)

    def oauth_test(self):
        # just for test
        pass

    def request_get_token(self, msg_b):
        # return msg_b and dst uri
        # send to server for token
        msg_str = msg_b.decode('utf-8')
        msg_j = json.loads(msg_str)

        pass

        print("call request_get_token")

        token = "1234"

        if token == "":
            return msg_str, msg_j["head"]["src"]

        msg_j["data"]["token"] = token

        msg_str = json.dumps(msg_j)

        print(msg_str, msg_j["head"]["dst"])


        return msg_str, msg_j["head"]["dst"]

    def proc_mode_request(self, msg_b):
        # use a new process call oauth check, if pass send msg to dst, if not send denied to src

        msg_s, dst_uri = self.request_get_token(msg_b)

        print(msg_s, dst_uri)

        sock_ipc = nnpy.Socket(nnpy.AF_SP, nnpy.BUS)
        sock_ipc.connect(dst_uri)
        sock_ipc.send(msg_s)
        sock_ipc.close()


    def proc_mode_reply(self, msg_b):
        pass

    def proc_mode_forward(self, msg_b):
        pass


    def msg_proc(self):
        while True:
            try:
                msg_bytes = self.local_sock.recv()
                # print(type(msg_bytes))
                msg_str = msg_bytes.decode('utf-8')
                msg = json.loads(msg_str)

                print(type(msg), msg)
                # print(type(msg["head"]["mode"]), msg["head"]["mode"])
                mode = msg["head"]["mode"]
                print(self.MODE_DICT)
                if mode in self.MODE_DICT:
                    print("call hanler")
                    self.MODE_DICT[mode](msg_bytes)
            except nnpy.errors.NNError as e:
                print(e)
                break

    def msg_parse(self, msg):
        method = msg["head"]["method"]
        if method in self.OPERAT_DICT:
            self.OPERAT_DICT[method]()

def main():
    router = Router()
    router.msg_proc()

if __name__ == '__main__':
    main()
